#include "UserDao.h"
#include "userBean.h"
#include "kisql.h"


UserDao *UserDao::sInstance = new UserDao();

static kisql *db;
static MYSQL_RES *result;
static MYSQL_ROW row;

UserDao::UserDao(){
    db = kisql::getInstance();
}

UserDao::~UserDao(){

}

UserDao* UserDao::getInstance(){
    return sInstance;
}

void UserDao::addUser(userBean mUserBean){

}

void UserDao::getUser(userBean* UserBean, userBean& retUser){

    char sql[1024] = {0};
    sprintf(sql, "select * from userinfo where username = \"%s\" and userpass = \"%s\"", UserBean->getUserName().c_str(), UserBean->getUserPass().c_str());

    if(mysql_query(db->getMysql(), sql)){
        perror("mysql query err");
        return;
    }else{ //select success
        result = mysql_store_result(db->getMysql());
        if(result){
            //int num_fields = mysql_num_fields(result);
            int num_rows = mysql_num_rows(result);

            for(int i = 0; i < num_rows; i++){
                row = mysql_fetch_row(result);
                if(row == nullptr){
                    break;
                }
                
                retUser.setUserName(row[0]); //username
                retUser.setUserPass(row[1]); //userpass
                retUser.setToken(row[2]); //usertoken
                cout << "ret: " << retUser.toString() << endl;
            }
        }
    }
    return;
}

bool UserDao::isUserRegister(string userToken, string &sid){

    string sql = "select * from game where token=\""+userToken+"\"";
    if(mysql_query(db->getMysql(), sql.c_str())){
        perror("mysql query err");
        return false; //never register
    }else{
        result = mysql_store_result(db->getMysql());
        if(result){
            //int num_fields = mysql_num_fields(result);
            int num_rows = mysql_num_rows(result);

            for(int i = 0; i < num_rows; i++){
                row = mysql_fetch_row(result);
                if(row < 0){
                    break;
                }
                sid = row[1];
                return true;
            }
        }
    }
    return false;
}

